package org.huawei.view;

import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import org.huawei.controller.SubmissionController;
import org.huawei.model.domain.Submission;

import java.sql.SQLException;
import java.util.List;

public class SubmissionDetailsView {

    private final Stage dialogStage;
    private SubmissionController submissionController;

    public SubmissionDetailsView(Stage parentStage, List<Submission> submissions) {
        submissionController = new SubmissionController(parentStage);

        dialogStage = new Stage();
        dialogStage.setTitle("作业提交详情");
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(parentStage);

        TableView<Submission> submissionTableView = new TableView<>();
        submissionTableView.setPrefWidth(950);
        submissionTableView.setPrefHeight(550);

        TableColumn<Submission, Integer> idCol = new TableColumn<>("提交ID");
        idCol.setCellValueFactory(new PropertyValueFactory<>("submissionId"));
        idCol.setPrefWidth(50);

        //TODO 改为名字
        TableColumn<Submission, String> submittedByCol = new TableColumn<>("提交者ID");
        submittedByCol.setCellValueFactory(new PropertyValueFactory<>("submittedBy"));
        submittedByCol.setPrefWidth(100);

        TableColumn<Submission, String> contentCol = new TableColumn<>("提交内容");
        contentCol.setPrefWidth(200);

        contentCol.setCellValueFactory(data -> {
            String fullContent = data.getValue().getSubmissionContent();
            String shortenedContent;
            // 如果内容超过30个字符，截取前30个字符并添加省略号
            if (fullContent.length() > 30) {
                shortenedContent = fullContent.substring(0, 30) + "...";
            } else {
                shortenedContent = fullContent;
            }
            return new SimpleStringProperty(shortenedContent);
        });

        TableColumn<Submission, String> dateCol = new TableColumn<>("提交日期");
        dateCol.setCellValueFactory(new PropertyValueFactory<>("submissionCreationDate"));
        dateCol.setPrefWidth(100);

        TableColumn<Submission, String> feedbackCol = new TableColumn<>("反馈");
        feedbackCol.setPrefWidth(200);
        feedbackCol.setCellValueFactory(data -> {
            String fullFeedback = data.getValue().getSubmissionFeedback();
            int maxLength = 30; // 截取的最大字符数
            String shortenedFeedback;

            // 如果内容超过 maxLength 个字符，截取并添加省略号
            if (fullFeedback.length() > maxLength) {
                shortenedFeedback = fullFeedback.substring(0, maxLength) + "...";
            } else {
                shortenedFeedback = fullFeedback;
            }
            return new SimpleStringProperty(shortenedFeedback);
        });

        feedbackCol.setCellFactory(col -> new TableCell<Submission, String>() {
            private final Button editButton = new Button("编辑");

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(item);  // 显示截取后的反馈内容
                    setGraphic(editButton);
                    editButton.setOnAction(event -> {
                        Submission submission = getTableView().getItems().get(getIndex());

                        // 创建自定义 Dialog 以编辑反馈内容
                        Dialog<ButtonType> dialog = new Dialog<>();
                        dialog.setTitle("编辑反馈");
                        dialog.setHeaderText("修改反馈内容");
                        TextArea textArea = new TextArea(submission.getSubmissionFeedback());
                        textArea.setWrapText(true);
                        dialog.getDialogPane().setContent(textArea);
                        textArea.setPrefSize(600, 400);

                        ButtonType okButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
                        dialog.getDialogPane().getButtonTypes().addAll(okButtonType, ButtonType.CANCEL);

                        dialog.showAndWait().ifPresent(response -> {
                            if (response == okButtonType) {
                                String newFeedback = textArea.getText();
                                submission.setSubmissionFeedback(newFeedback);  // 更新反馈内容
                                setText(newFeedback.length() > 30 ? newFeedback.substring(0, 30) + "..." : newFeedback);  // 更新表格显示
                                try {
                                    submissionController.updateSubmissionInDatabase(submission);  // 更新数据库
                                } catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }
                                getTableView().refresh();  // 刷新表格
                            }
                        });
                    });
                    setContentDisplay(ContentDisplay.RIGHT);
                }
            }
        });


        TableColumn<Submission, Double> gradeCol = new TableColumn<>("成绩");
        gradeCol.setCellValueFactory(new PropertyValueFactory<>("submissionGrade"));
        gradeCol.setPrefWidth(120);
        gradeCol.setCellFactory(col -> new TableCell<Submission, Double>() {
            private final Button editButton = new Button("编辑");
            @Override
            protected void updateItem(Double item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(String.valueOf(item));
                    setGraphic(editButton);
                    editButton.setOnAction(event -> {
                        Submission submission = getTableView().getItems().get(getIndex());

                        TextInputDialog dialog = new TextInputDialog(String.valueOf(item));
                        dialog.setTitle("编辑成绩");
                        dialog.setHeaderText("修改成绩");
                        dialog.setContentText("请输入成绩 (0-100):");

                        dialog.showAndWait().ifPresent(newGradeStr -> {

                            double newGrade = Double.parseDouble(newGradeStr);
                            if (newGrade < 0 || newGrade > 100) {
                                AlartView.alart(dialogStage, "成绩必须在0到100之间!");
                            } else {
                                submission.setSubmissionGrade(newGrade);
                                setText(String.valueOf(newGrade));
                                try {
                                    submissionController.updateSubmissionInDatabase(submission);
                                }
                                catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }
                                getTableView().refresh();
                            }
                        });
                    });
                    setContentDisplay(ContentDisplay.RIGHT);
                }
            }
        });

        TableColumn<Submission, Void> submissionDetailsColumn = new TableColumn<>("作业详情");
        submissionDetailsColumn.setPrefWidth(80);
        Callback<TableColumn<Submission, Void>, TableCell<Submission, Void>> cellFactory = new Callback<>() {
            @Override
            public TableCell<Submission, Void> call(final TableColumn<Submission, Void> param) {
                final TableCell<Submission, Void> cell = new TableCell<>() {
                    private final Button detailsButton = new Button("提交详情");

                    {
                        detailsButton.setOnAction(event -> {
                            Submission submission = getTableView().getItems().get(getIndex());
                            String submissionContent = submission.getSubmissionContent();

                            // Create a dialog to display the submission content
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setTitle("提交内容");
                            alert.setHeaderText("作业提交详情");

                            // 使用 TextArea 显示作业内容，并使其不可编辑
                            TextArea textArea = new TextArea(submissionContent);
                            textArea.setWrapText(true);
                            textArea.setEditable(false);  // 禁止编辑

                            // 使用 ScrollPane 包裹 TextArea
                            ScrollPane scrollPane = new ScrollPane(textArea);
                            scrollPane.setFitToWidth(true);  // 自动调整宽度
                            scrollPane.setFitToHeight(true); // 自动调整高度

                            // 设置 ScrollPane 的大小
                            scrollPane.setPrefSize(800, 500);

                            // 将 ScrollPane 设置为弹窗的内容
                            alert.getDialogPane().setContent(scrollPane);

                            alert.showAndWait();
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty || getIndex() < 0) {
                            setGraphic(null);
                        } else {
                            setGraphic(detailsButton); // Set the button as the graphic for the cell
                        }
                    }
                };
                return cell;
            }
        };


        submissionDetailsColumn.setCellFactory(cellFactory);

        // 将列添加到表格中
        submissionTableView.getColumns().addAll(idCol, submittedByCol, contentCol, submissionDetailsColumn, dateCol, feedbackCol, gradeCol);

        // 添加数据
        submissionTableView.getItems().addAll(submissions);

        // 布局：使用 BorderPane 将表格居中
        BorderPane root = new BorderPane();
        root.setCenter(submissionTableView);
        root.setPadding(new Insets(10));

        // 添加关闭按钮
        Button closeButton = new Button("关闭");
        closeButton.setOnAction(e -> dialogStage.close());
        VBox bottomBox = new VBox(closeButton);
        bottomBox.setPadding(new Insets(10));
        root.setBottom(bottomBox);

        // 设置场景并显示
        Scene scene = new Scene(root);
        dialogStage.setScene(scene);
    }

    // 显示弹窗
    public void showAndWait() {
        dialogStage.showAndWait();
    }
}

